package com.qk.web.filter;


import cn.hutool.core.util.ObjectUtil;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter("/*") //注释后过滤器不生效
public class LoginFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HEADER_NAME="token";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.将请求对象和响应对象强转为HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.获取请求路径，
        String path = request.getRequestURI();
        log.info("拦截到请求路径：{}",path);
        //4.判断是否是登录请求，如果是登录请求则放行
        boolean isLoginReq = ObjectUtil.equals(LOGIN_PATH, path);
        if (isLoginReq){
            filterChain.doFilter(request,response);
            return;
        }
        //5，获取请求头中的token，判断它是否为空，为空则拦截
        String token = request.getHeader(TOKEN_HEADER_NAME);
        if (ObjectUtil.isEmpty( token)){
            response.setStatus(401);
            return;
        }

        //6，校验token，如果验证失败则拦截
        try {
            Claims claims = JwtUtils.parseToken(token);
            //7获取用户信息  todo
            String username = claims.get("username", String.class);
            log.info("用户名是：{}",username);
            Object id = claims.get("id");
            log.info("用户id是：{}",id);
            //8，放行
            filterChain.doFilter(request,response);
            return;
        }catch (Exception e){
            log.error("token验证失败",e);
            response.setStatus(401);
        }
    }
}
